﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HR60_PanelSoft.Model;
using HR60_PanelSoft.Model.BaseModel;
using HR60_PanelSoft.View.Base;
using HR60_PanelSoft.View.TabForms.ListItems;

namespace HR60_PanelSoft.View.TabForms
{
	public partial class PanelForm : BaseForm
	{
		public PanelForm()
		{
			InitializeComponent();

			// 初始化样式列表
			IDictionary styleMap = new Dictionary<string, UIStyle>();
			styleMap.Add("项目默认选项", UIStyle.NULL);
			styleMap.Add("清爽", UIStyle.QingShuang);
			styleMap.Add("奢华", UIStyle.SheHua);
			selStyle.bindData(styleMap);

			// 初始化E++列表
			IDictionary eMap = new Dictionary<string, EplusType>();
			eMap.Add("未定义", EplusType.NULL);
			eMap.Add("灯光窗帘", EplusType.LampWin);
			eMap.Add("中央空调", EplusType.CentralAircon);
			eMap.Add("中央供暖", EplusType.CentralHeating);
			eMap.Add("新风系统", EplusType.CentralNewWind);
			eMap.Add("背景音乐", EplusType.BGM);
			selEplus.bindData(eMap);
		}

		// 绑定数据
		public override void refreshFormData(System.Collections.Generic.IDictionary<string, object> dataMap)
		{
			HR60_PanelSoft.Model.Panel panel = (HR60_PanelSoft.Model.Panel)dataMap["panel"];

			txtName.Value = panel.name;
			txtIndex.Value = panel.index.ToString();
			selStyle.Value = panel.style;
			selEplus.Value = panel.eplusType;
			selType.bindData((IList)panelTypes, "name");

			// 负载线路列表
			cleanPinItem();

			foreach (Pin pin in panel.loadPins)
			{
				appendPinItem(pin);
			}
			if (panel.type.hasM485Model)
			{
				appendPinItem(panel.m485Pin);
			}
		}

		// 数据修改事件
		public override void onFormChanged(BaseFormControl sender, System.EventArgs e)
		{
			windowMain.doSavePanel((HR60_PanelSoft.Model.Panel)this.bindDataMap["panel"], this.getFields());
		}

		private void mapPin2Device(Device dev, LoadPin pin)
		{
			if (pin.type == PinType.M485) return;

			// 取消负载连接
			if (dev == null)
			{

			}

			// 查找可用的pin列表
			IList<LoadPin> list = new List<LoadPin>();
			bool findFlag = false;
			foreach (LoadPin mpin in ((HR60_PanelSoft.Model.Panel)this.bindDataMap["panel"]).loadPins)
			{
				if (mpin == pin)
				{
					findFlag = true;
					list.Add(mpin);
					continue;
				}
				if (findFlag && mpin.connectedDevice != null)
				{
					list.Add(mpin);
				}
			}

			// 判断pin是否够用
			if (dev.type.pinLen > list.Count)
			{
				throw new Exception("空闲的负载线路不足");
			}

		}


		#region Pin列表操作

		IList<Control> pinItems = new List<Control>();

		private void appendPinItem(Pin pin)
		{
			PinItem pinItem = new PinItem(pin, pin.type == PinType.M485 ? "485" : ((LoadPin)pin).displayName);
			mainPanel.Controls.Add(pinItem);
			pinItems.Add(pinItem);
		}

		private void cleanPinItem()
		{
			foreach (Control pinItem in pinItems)
			{
				mainPanel.Controls.Remove(pinItem);
			}
		}

		#endregion
	}
}
